//
//  ShoppingTableViewController.swift
//  ZTC_Final
//
//  Created by xy Man on 2022/5/26.
//

import UIKit

class ShoppingTableViewController: UITableViewController {

    @IBOutlet weak var totalPrice: UILabel!
    
    @IBAction func payPressed(_ sender: Any) {
        let queryre = getQueryData(sql: "SELECT * FROM history;")
        let maxIdquery = getQueryData(sql: "SELECT MAX(id) FROM history;")
        var maxId:Int
        var bookname:String
        var number:Int
        if queryre!.count == 0{
            maxId = 1
        }else{
            maxId = maxIdquery![0]["MAX(id)"] as! Int + 1
        }
        let time:String = getCurrentTime()
        for book in loadData()!{
            bookname = book["bookname"] as! String
            number = book["number"] as! Int
            doNonSql(sql: "INSERT INTO history VALUES(\(maxId),'\(username!)','\(bookname)',\(number),'\(time)',\(allPrice));")
        }
//        let nav3 = self.tabBarController!.viewControllers![2] as! UINavigationController
//        let historyVC = nav3.viewControllers.first as! HistoryTableViewController
//        historyVC.tableView.reloadData()

    }
    // 正在将cell的值传递给shoppingVC
//    var bookname:String = ""
//    var bookPrice:String = ""
//    var pic_path = ""
//    var hasBuy = ""
    
    var username:String?
    var queryres:[[String : AnyObject]]?
    var allPrice:Double = 0
    override func viewDidLoad() {
        super.viewDidLoad()
//        print("购物车VC传递的用户名\(username)")
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
        let xib = UINib(nibName: "BookTableViewCell", bundle: nil)
        tableView.register(xib, forCellReuseIdentifier: "shoppingCell")
        tableView.rowHeight = 199

    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return loadData()!.count
    }

    func loadData()->[[String : AnyObject]]?{
        let sqlite = SQLiteManager.sharedInstance
        if !sqlite.openDB() {return[]}
        let tmpsql = "SELECT bookname, number FROM shopping WHERE username='\(username!)' AND number>0;"
        let queryres = sqlite.execQuerySQL(sql: tmpsql)
        sqlite.closeDB()
        return queryres
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "shoppingCell", for: indexPath) as! BookTableViewCell
       // Configure the cell...
        let title = loadData()![indexPath.row]["bookname"] as! String
        cell.bookName.text = title
        cell.hasBuyNum.text = "\(loadData()![indexPath.row]["number"] as! Int)"
        let sqlite = SQLiteManager.sharedInstance
        if !sqlite.openDB(){return cell}
        let tmpsql = "SELECT price, pic_path FROM book WHERE title='\(loadData()![indexPath.row]["bookname"] as! String)';"
        let tmpres = sqlite.execQuerySQL(sql: tmpsql)
        sqlite.closeDB()
        cell.bookPrice.text = "\(tmpres![0]["price"] as! Double)元/本"
        let pic_path = tmpres![0]["pic_path"] as! String
        let nsurl = NSURL(string: pic_path)
        let nsd = NSData(contentsOf: nsurl! as URL)
        let myImage = UIImage(data: nsd! as Data)
        cell.bookImage.image = myImage
        let num = loadData()![indexPath.row]["number"] as! Int
        let price = tmpres![0]["price"] as! Double
        let addition = Double(num)*price
        totalPrice.text = String(format: "%.2f", addition+allPrice)+"元"
        allPrice = allPrice + addition
        return cell
    }
    
    override func viewWillAppear(_ animated: Bool) {
 
        tableView.reloadData()
        allPrice = 0
    }
    
    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {

            // 更新总价
            let sqlite = SQLiteManager.sharedInstance
            if !sqlite.openDB(){return}
            let tmpsql = "SELECT price, pic_path FROM book WHERE title='\(loadData()![indexPath.row]["bookname"] as! String)';"
            let tmpres = sqlite.execQuerySQL(sql: tmpsql)
            let num = loadData()![indexPath.row]["number"] as! Int
            let price = tmpres![0]["price"] as! Double
            let addition = Double(num)*price
            totalPrice.text = String(format: "%.2f", (allPrice-addition))+"元"
            allPrice = allPrice - addition
            // 在数据库中将该用户与该书的本数置为0
            let title = loadData()![indexPath.row]["bookname"] as!String
            let delSql = "UPDATE shopping SET number=0 WHERE username='\(username!)' AND bookname='\(title)';"
            
            if !sqlite.openDB(){return}
            if !sqlite.execNoneQuerySQL(sql: delSql){return}
            sqlite.closeDB()
            let nav = self.navigationController
            let a = Int(nav?.tabBarItem.badgeValue ?? "0")
            nav?.tabBarItem.badgeValue = "\(a! - num)"
            
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .automatic)

        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    
    func getQueryData(sql:String)->[[String : AnyObject]]?{
        let sqlite = SQLiteManager.sharedInstance
        if !sqlite.openDB(){return []}
        let queryres = sqlite.execQuerySQL(sql: sql)
        sqlite.closeDB()
        return queryres
    }
    
    func doNonSql(sql:String)->Void{
        let sqlite = SQLiteManager.sharedInstance
        if !sqlite.openDB(){return}
        if !sqlite.execNoneQuerySQL(sql: sql){return}
        sqlite.closeDB()
    }
    
    func getCurrentTime()->String{
        let date = Date()
        let timeFormmater = DateFormatter()
        timeFormmater.dateFormat = "yyyy-MM-dd HH:mm:ss"
//        print(timeFormmater.string(from: date))
        return timeFormmater.string(from: date)
    }
    
    
//    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//        <#code#>
//    }
    

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
        let successful = segue.destination as! PayViewController
        successful.price = totalPrice.text!
    }
    

}
